package com.supor.md_video.tools;

import android.app.Activity;
import android.content.Context;
import android.graphics.Point;
import android.graphics.Rect;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;

import androidx.viewbinding.ViewBinding;
import androidx.viewpager2.widget.ViewPager2;

import com.android.baseconfig.base.BaseSharedPreferences;
import com.android.baseconfig.common.utils.Logc;
import com.pili.pldroid.player.PLOnInfoListener;
import com.pili.pldroid.player.PLOnVideoSizeChangedListener;
import com.pili.pldroid.player.widget.PLVideoTextureView;
import com.supor.aiot.common.app.Constants;
import com.supor.md_video.R;
import com.supor.md_video.adapter.VideoListViewAdapter;
import com.youku.upsplayer.data.GetInfoResult;

import java.io.IOException;

public class VideoListPlayerManager {

    private PLVideoTextureView plVideoTextureView;
    //    private ImageView mImCoverView;
    private VideoListViewAdapter mVideoListViewAdapter;
    private int currentViewPosition;
    private int oldPosition;
    private int listViewLife;
    private Activity mContext;
    private ViewPager2.OnPageChangeCallback pageChangeCallback;
    private ViewPager2 viewPager2;
    private FrameLayout playerContainer;
    private ImageView mIvPlay;
    private AudioManager audioManager;
    private AudioManager.OnAudioFocusChangeListener afChangeListener;
    private View layoutNetCheck;
    private boolean isNetAgree;
//    private int widthPixels;
//    private int heightPixels;

    public void init(Activity mContext) {
        this.mContext = mContext;
        isNetAgree = BaseSharedPreferences.getBoolean(mContext, Constants.Key.VIDEO_NET_AGREE, false);
//        initScreenSize(mContext);
        getTextureView();
    }

    public void bindViewPager(ViewPager2 viewPager2) {
        this.viewPager2 = viewPager2;
    }

    private PLVideoTextureView getTextureView() {
        if (null == plVideoTextureView) {
            plVideoTextureView = new PLVideoTextureView(mContext);
//            plVideoTextureView.setMediaController(new MediaController(mContext));
//            plVideoTextureView.setMediaController(new VideoControllerView(mContext));
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            params.gravity = Gravity.CENTER;
            plVideoTextureView.setLayoutParams(params);
//            plVideoTextureView.setDisplayAspectRatio(PLVideoTextureView.ASPECT_RATIO_PAVED_PARENT);
            plVideoTextureView.setDisplayAspectRatio(PLVideoTextureView.ASPECT_RATIO_FIT_PARENT);
//            plVideoTextureView.setDisplayAspectRatio(PLVideoTextureView.ASPECT_RATIO_16_9);
            plVideoTextureView.setLooping(true);
//            AVOptions options = new AVOptions();
//            options.setInteger(AVOptions.KEY_PREPARE_TIMEOUT, 10 * 1000);
//            options.setInteger(AVOptions.KEY_LIVE_STREAMING, 0);
//            options.setString(AVOptions.KEY_CACHE_DIR, Config.DEFAULT_CACHE_DIR);
//            plVideoTextureView.setAVOptions(options);
            getPlayerContainer().addView(plVideoTextureView);
            getPlayerContainer().addView(getPlayIco());
        }
        return plVideoTextureView;
    }

    private FrameLayout getPlayerContainer() {
        if (null == playerContainer) {
            playerContainer = new FrameLayout(mContext);
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
//            params.gravity = Gravity.CENTER;
            playerContainer.setLayoutParams(params);
            playerContainer.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (getTextureView().isPlaying()) {
                        onPause();
                    } else {
                        onResume();
                    }
                }
            });
        }
        return playerContainer;
    }

    private ImageView getPlayIco() {
        if (null == mIvPlay) {
            mIvPlay = new ImageView(mContext);
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    mContext.getResources().getDimensionPixelOffset(R.dimen.dp_64),
                    mContext.getResources().getDimensionPixelOffset(R.dimen.dp_64)
            );
            params.gravity = Gravity.CENTER;
            mIvPlay.setLayoutParams(params);
            mIvPlay.setBackgroundResource(R.mipmap.ic_video_play);

            mIvPlay.setVisibility(View.INVISIBLE);
        }
        return mIvPlay;
    }

    public void bindAdapter(VideoListViewAdapter adapter) {
        mVideoListViewAdapter = adapter;
    }

    public void setVideoPath(String mVideoPath) throws IOException {
        plVideoTextureView.setVideoPath(mVideoPath);
    }

    public ViewPager2.OnPageChangeCallback getPageChangeCallBack() {
        if (null == pageChangeCallback) {
            pageChangeCallback = new ViewPager2.OnPageChangeCallback() {
                @Override
                public void onPageScrollStateChanged(int state) {
                    super.onPageScrollStateChanged(state);
                    switch (state) {
                        case 1:
//                            stopListPlay();
//                            removeRunnable();
                            break;
                        case 0:
//                            nextVideo(position);
                            startListPlay();
                            break;
                    }
                }

                @Override
                public void onPageSelected(int position) {
                    super.onPageSelected(position);
                    currentViewPosition = position;
                    viewPositionChange();
                }
            };
        }
        return pageChangeCallback;
    }

    public void viewPositionChange() {
        if (listViewLife == 0) {
            listViewLife = 1;
            if (isNetAgree || isWifi(mContext)) {
                startListPlay();
            } else {
                showNetCheckView();
            }
        } else {
            stopListPlay();
        }
    }

    private void showNetCheckView() {
        layoutNetCheck = View.inflate(mContext, R.layout.layout_video_list_net_check, null);
        ((ViewGroup) mContext.getWindow().getDecorView()).addView(layoutNetCheck);
        layoutNetCheck.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        layoutNetCheck.findViewById(R.id.ll_check_agree).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isNetAgree = !isNetAgree;
                if (isNetAgree) {
                    layoutNetCheck.findViewById(R.id.iv_check_agree).setBackgroundResource(R.mipmap.ic_video_net_check_agree);
                } else {
                    layoutNetCheck.findViewById(R.id.iv_check_agree).setBackgroundResource(R.drawable.shape_video_net_check_agree);
                }
            }
        });
        layoutNetCheck.findViewById(R.id.tv_continue).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BaseSharedPreferences.setBoolean(mContext, Constants.Key.VIDEO_NET_AGREE, isNetAgree);
                startListPlay();
                layoutNetCheck.setVisibility(View.GONE);
            }
        });
        layoutNetCheck.findViewById(R.id.tv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mContext.finish();
            }
        });
//        BaseSharedPreferences.getBoolean(mContext, Constants.Key.VIDEO_NET_AGREE, false);
    }

    public void stopListPlay() {
//        currentViewPosition = position;
//        if (currentViewPosition == oldPosition && listViewLife != 0) {
//            return;
//        }

        ViewGroup oldContainer = (ViewGroup) getPlayerContainer().getParent();
        if (null != oldContainer) {
            oldContainer.removeAllViews();
        }

        if (getTextureView().isPlaying()) {
            getTextureView().pause();
        }
        View oldCoverView = mVideoListViewAdapter.getViewByPosition(oldPosition, R.id.iv_cover);
        if (null != oldCoverView && oldCoverView.getVisibility() != View.VISIBLE) {
            oldCoverView.setVisibility(View.VISIBLE);
        }
        View newCoverView = mVideoListViewAdapter.getViewByPosition(currentViewPosition, R.id.iv_cover);
        if (null != newCoverView && newCoverView.getVisibility() != View.VISIBLE) {
            newCoverView.setVisibility(View.VISIBLE);
        }
    }

    public void startListPlay() {
        if (currentViewPosition == oldPosition && plVideoTextureView.isPlaying()) {
            return;
        }
        oldPosition = currentViewPosition;
        FrameLayout container = (FrameLayout) mVideoListViewAdapter.getViewByPosition(oldPosition, R.id.fl_container);
        if (null == container) {
            return;
        }
        getPlayIco().setVisibility(View.INVISIBLE);
        FrameLayout playView = getPlayerContainer();
        if (null != playView.getParent()) {
            ((ViewGroup) playView.getParent()).removeAllViews();
        }
        container.addView(playView);
        getTextureView().setVideoPath(mVideoListViewAdapter.getData().get(oldPosition).getHighVertical());
//        getTextureView().setVideoPath("https://outin-1b20dde6136711eb8a4a00163e1c35d5.oss-cn-shanghai.aliyuncs.com/sv/5b73019f-1778a4bea01/5b73019f-1778a4bea01.mp4");
        getTextureView().setOnInfoListener(new PLOnInfoListener() {
            @Override
            public void onInfo(int what, int i1) {
                if (what == PLOnInfoListener.MEDIA_INFO_VIDEO_RENDERING_START) {
                    View viewCover = mVideoListViewAdapter.getViewByPosition(oldPosition, R.id.iv_cover);
                    if (null != viewCover) {
                        viewCover.setVisibility(View.INVISIBLE);
                    }
                }
            }
        });
        getTextureView().setOnVideoSizeChangedListener(new PLOnVideoSizeChangedListener() {
            @Override
            public void onVideoSizeChanged(int width, int height) {
//                View root = mContext.getWindow().getDecorView().getRootView();
//                int[] location = new int[2];
//                root.getLocationOnScreen(location);

                Rect rect = new Rect();
                mContext.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);

                int widthPixels = rect.right - rect.left;
                int heightPixels = rect.bottom - rect.top;
                int tpHeight = (int) Math.min(widthPixels * 1.0f / width * height, heightPixels);
//                int tpHeight = (int) (widthPixels * 1.0f / width * height);

                int barheight = 0;
                if (isNavigationBarShow()) {
                    barheight = getNavigationBarHeight();
                }
                int tpPaddingTop = (heightPixels - tpHeight) / 2 + barheight;
                tpPaddingTop = Math.max(tpPaddingTop, mContext.getResources().getDimensionPixelOffset(R.dimen.dp_52));

                if (null != toolBar) {
                    Logc.d("onVideoSizeChanged width:" + width +
                            " height:" + height
                            + " widthPixels:" + widthPixels
                            + " heightPixels:" + heightPixels
                            + " tpHeight:" + tpHeight
                            + " dp_52:" + mContext.getResources().getDimensionPixelOffset(R.dimen.dp_52)
                            + " tpPaddingTop:" + tpPaddingTop
                            + " barheight:" + barheight
                    );
                    toolBar.setPadding(0, tpPaddingTop, 0, 0);
                }
            }
        });

        getAudioFocus();
        getTextureView().start();
    }

    private void getAudioFocus() {
        if (null == audioManager) {
            audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
        }
        if (null == audioManager) {
            afChangeListener = new AudioManager.OnAudioFocusChangeListener() {
                public void onAudioFocusChange(int focusChange) {
                    if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
                        stopListPlay();
                    } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) {
                    } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) {
                    } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
                    }
                }
            };
        }

        // Request audio focus for playback
        int result = audioManager.requestAudioFocus(afChangeListener,
                // Use the music stream.
                AudioManager.STREAM_MUSIC,
                // Request permanent focus.
                AudioManager.AUDIOFOCUS_GAIN);
        Logc.d("AUDIO_FOCUS", "result = " + result);

//        if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
//
//        }
    }

    public int getCurrentViewPosition() {
        return currentViewPosition;
    }

    public void onPause() {
        if (null != plVideoTextureView) {
            plVideoTextureView.pause();
        }
        if (null != mIvPlay) {
            mIvPlay.setVisibility(View.VISIBLE);
        }
    }

    public void onResume() {
        if (null != plVideoTextureView) {
            plVideoTextureView.start();
        }
        if (null != mIvPlay) {
            mIvPlay.setVisibility(View.INVISIBLE);
        }
    }

    public void destoryManager() {
        if (null != plVideoTextureView) {
            plVideoTextureView.stopPlayback();
        }
    }

    private static boolean isWifi(Context mContext) {
        ConnectivityManager connectivityManager = (ConnectivityManager) mContext
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
        if (activeNetInfo != null
                && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
            return true;
        }
        return false;
    }

    private ViewGroup toolBar;

    public void bindToolBar(ViewGroup toolBar) {
        this.toolBar = toolBar;
    }

//    private void initScreenSize(Activity activity) {
////        DisplayMetrics outMetrics = new DisplayMetrics();
////        activity.getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
////        widthPixels = outMetrics.widthPixels;
////        heightPixels = outMetrics.heightPixels;
//
//        View root = mContext.getWindow().getDecorView().getRootView();
//        int[] location = new int[2];
//        root.getLocationOnScreen(location);
//        widthPixels = location[0];
//        heightPixels = location[1];
//    }

    /**
     * 底部导航是否显示
     */
    private Boolean isNavigationBarShow() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            Display display = mContext.getWindowManager().getDefaultDisplay();
            Point size = new Point();
            Point realSize = new Point();
            display.getSize(size);
            display.getRealSize(realSize);
            return realSize.y != size.y;
        } else {
            boolean menu = ViewConfiguration.get(mContext).hasPermanentMenuKey();
            boolean back = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK);
            return !(menu || back);
        }
    }

    /**
     * 获取底部导航条高度
     */
    private int getNavigationBarHeight() {
        if (!isNavigationBarShow()) {
            return 0;
        }
        int resourceId = mContext.getResources().getIdentifier("navigation_bar_height", "dimen", "android");
        //获取NavigationBar的高度
        return mContext.getResources().getDimensionPixelSize(resourceId);
    }


}